﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL;
using BLL;
using System.Data;

public partial class admin_Products_Details : System.Web.UI.Page
{
  ProdCateBLL categoryData = new ProdCateBLL();
  ProductBLL productData = new ProductBLL();
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
      Session["url_back_admin"] = Request.RawUrl;
      LoadTitle();
      LoadCategory();
      LoadStatus();
      //LoadColour();
      LoadLabel();
      LoadSize();
      LoadBrand();
      LoadrptColor();
      LoadControl();
      if (Request.QueryString["Id"] != null)
        Filldata();
      else
      {
        txtView.Text = "0";
        trCreatedDate.Visible = false;
      }
    } 
  }


  void LoadControl()
  {
      string a = string.Empty;
      

      int CateId = -1;
      if (dropParent.Items.Count > 0)
          CateId = Convert.ToInt32(dropParent.SelectedValue);
      int CateParent = categoryData.GetById(CateId).Parent;
      if (CateParent != 0)
      {
          infoOk.Visible = true;
          TabContainer1.Visible = true;
      }
      else
      {
          infoOk.Visible = false;
          TabContainer1.Visible = false;
      }

      if (Request.QueryString["Id"] != null)
      {
          infoOk.Visible = true;
          TabContainer1.Visible = true;
      }
  }


  private void LoadBrand()
  {
    if (dropParent.SelectedIndex == -1) return;
    int mode = -1;

    if (Request.QueryString["Id"] == null)
    {
      try { mode = categoryData.GetById(Convert.ToInt32(dropParent.SelectedValue)).Id; }
      catch { }
    }
    else if (Request.QueryString["Id"] != null)
    {
      try
      {
        var product = productData.GetById(Request.QueryString["Id"]);
        mode = categoryData.GetById(product.CategoryId).Id;
      }
      catch { }
    }
    BrandBLL data = new BrandBLL();
    var list = data.GetByMode(mode);
    dropBrand.DataSource = list;
    dropBrand.DataTextField = "Name";
    dropBrand.DataValueField = "Id";
    dropBrand.DataBind();
  }

  private void LoadStatus()
  {
    StatusBLL data = new StatusBLL();
    dropStatus.DataSource = data.GetAll();
    dropStatus.DataTextField = "Name";
    dropStatus.DataValueField = "Id";
    dropStatus.DataBind();
  }
  private void LoadLabel()
  {
      LabelBLL data = new LabelBLL();
      dropLabel.DataSource = data.GetAll();
      dropLabel.DataTextField = "Name";
      dropLabel.DataValueField = "Id";
      dropLabel.DataBind();
      ListItem itemRoot = new ListItem("Không chọn", "0");
      dropLabel.Items.Insert(0, itemRoot);
  }
  private void LoadColour()
  {
    //checkColour.Items.Clear();

    if(dropParent.SelectedIndex ==-1) return;
    int mode = -1;

    if (Request.QueryString["Id"] == null)
    {
        try { mode = categoryData.GetById(Convert.ToInt32(dropParent.SelectedValue)).Mode;}
        catch { }
    }
    else if (Request.QueryString["Id"] != null)
    {
      try
      {
        var product = productData.GetById(Request.QueryString["Id"]);
        mode = categoryData.GetById(product.CategoryId).Mode;
      }
      catch { }
    }
    ColourBLL data = new ColourBLL();
    var list = data.GetByMode(mode);
    List<Image> listImage = new List<Image>();
    for (int i = 0; i < list.Count; i++)
    {
     // checkColour.Items.Add(new ListItem(list[i].Name, list[i].Id.ToString()));
      //imageColor.ImageUrl = "~/Images/Colour/" + list[i].Image.ToString().Trim();
      //checkColour.Items.Add(new List<Image>(imageColor));
    }
  }

  void LoadrptColor()
  {
      if (dropParent.SelectedIndex == -1) return;
      int mode = -1;
      if (Request.QueryString["Id"] == null)
      {
          try { mode = categoryData.GetById(Convert.ToInt32(dropParent.SelectedValue)).Id; }
          catch { }
      }
      else if (Request.QueryString["Id"] != null)
      {
          try
          {
              var product = productData.GetById(Request.QueryString["Id"]);
              mode = categoryData.GetById(product.CategoryId).Id;
          }
          catch { }
      }
      ColourBLL data = new ColourBLL();
      var list = data.GetByMode(mode);
      DataTable tbColor = Myfunction.ConvertToDataTable(list);
      rptColor.DataSource = tbColor;
      rptColor.DataBind();
  }
  private void LoadSize()
  {
    checkSize.Items.Clear();

   if (dropParent.SelectedIndex == -1) return;
    int mode = -1;
    if (Request.QueryString["Id"] == null)
    {
      try { mode = categoryData.GetById(Convert.ToInt32(dropParent.SelectedValue)).Id; }
      catch { }
    }
    else if (Request.QueryString["Id"] != null)
    {
      try
      {
        var product = productData.GetById(Request.QueryString["Id"]);
        mode = categoryData.GetById(product.CategoryId).Id;
      }
      catch { }
    }

    SizeBLL data = new SizeBLL();
    var list = data.GetByMode(mode);
    foreach (var item in list)
    {
      checkSize.Items.Add(new ListItem(item.Name, item.Id.ToString()));
    }
  }

  ProductInSizeBLL ptsData = new ProductInSizeBLL();
  ProductInColourBLL picData = new ProductInColourBLL();
  private void Filldata()
  {
    

    string id = Request.QueryString["Id"];
    Product product = productData.GetById(id);
    txtMaSP.Text = product.Id;
    txtMaSP.Enabled = false;
    txtName.Text = product.Name;
    txtName_En.Text = product.Name_En;
    txtOrigin.Text = product.LinkGoc;
    txtDescription.Text = product.UuDai;
    dropStatus.SelectedValue = product.Status.ToString();
    dropBrand.SelectedValue = product.Brand.ToString();
    dropLabel.SelectedValue = product.LabelId.ToString();
    if (product.Cost != null)
      txtCost.Text = String.Format("{0:0}", ((decimal)product.Cost));
    if(product.Cost_Sale != null)
      txtCost_Sale.Text = String.Format("{0:0}", ((decimal)product.Cost_Sale));
    //Load size
    var listSize = ptsData.GetByProductId(id);
    foreach (var item in listSize)
	    {
		    for(int i =0;i<checkSize.Items.Count; i++)
        {
          if(checkSize.Items[i].Value == item.IdSize.ToString())
            checkSize.Items[i].Selected = true;
        }
	    }

    //Load color
    //var listColor = picData.GetByProductId(id);
    //foreach (var item in listColor)
    //  {
    //    for(int i =0; i<checkColour.Items.Count; i++)
    //      if(checkColour.Items[i].Value == item.IdColour.ToString())
    //        checkColour.Items[i].Selected = true;
    //  }

    //Load image
    if (product.Image_01 != null)
    {
      image_01.ImageUrl = "~/Images/Product/thumb/" + product.Image_01;
      image_01.Visible = true;
    }
    if (product.Image_02 != null)
    {
      image_02.ImageUrl = "~/Images/Product/thumb/" + product.Image_02;
      image_02.Visible = true;
      check_DelImage_02.Visible = true;

    }
    if (product.Image_03 != null)
    {
      image_03.ImageUrl = "~/Images/Product/thumb/" + product.Image_03;
      image_03.Visible = true;
      check_DelImage_03.Visible = true;
    }
    if (product.Image_04 != null)
    {
      image_04.ImageUrl = "~/Images/Product/thumb/" + product.Image_04;
      image_04.Visible = true;
      check_DelImage_04.Visible = true;
    }
    if (product.Image_05 != null)
    {
      image_05.ImageUrl = "~/Images/Product/thumb/" + product.Image_05;
      image_05.Visible = true;
      check_DelImage_05.Visible = true;
    }

    if (product.Image_06 != null)
    {
      image_06.ImageUrl = "~/Images/Product/thumb/" + product.Image_06;
      image_06.Visible = true;
      check_DelImage_06.Visible = true;
    }

    fckEditor.Value = HttpUtility.HtmlDecode(product.Content);
    //fckEditor_En.Value = HttpUtility.HtmlDecode(product.Content_En);

    txtQuantity.Text = product.Quantity.ToString();
     dropParent.SelectedValue = product.CategoryId.ToString();
       
    if (product.isKM)
      checkKM.Checked = true;
    if (product.isHot)
      checkHot.Checked = true;

    txtTag.Text = product.Tag;
    txtView.Text = product.View.ToString();
    txtCreatedDate.Text = product.CreatedDate.ToShortDateString();

    if (product.isEnable == true) radioEnable.Checked = true;
    else radioVisible.Checked = true;       
  }
  
  private void LoadCategory()
  {
    dropParent.Items.Clear();
    ShowChild(0, " - - ");
  }

  private void ShowChild(int parentId, string space)
  {
      List<ProdCate> listDataSource = categoryData.GetByParent(parentId);

      foreach (ProdCate item in listDataSource)
      {
          ListItem obj = new ListItem(space + item.Name, item.Id.ToString());
          dropParent.Items.Add(obj);

          ShowChild(item.Id, space + "- - - ");
      }
  }
  private void LoadTitle()
  {
    if (Request.QueryString["Id"] != null)
    {
      h3Title.InnerText = "Chỉnh sửa thông tin sản phẩm";
    }
  }
  private bool isValidate()
  {
    if (txtMaSP.Text == "")
    {
      Myfunction.ThongBao(lbThongBao, "Mã sản phẩm không được để trống !");
      txtMaSP.Focus();
      return false;
    }
    if (Request.QueryString["Id"] == null && productData.IsCheckExitsId(txtMaSP.Text))
    {
      Myfunction.ThongBao(lbThongBao, "Mã sản phẩm này đã tồn tại !");
      txtMaSP.Focus();
      return false;
    }
    if (txtName.Text == "")
    {
      Myfunction.ThongBao(lbThongBao, "Tên sản phẩm không được để trống !");
      txtName.Focus();
     return false;
    }
    if (dropParent.SelectedIndex == -1)
    {
      Myfunction.ThongBao(lbThongBao, "Chọn danh mục !");
      return false;
    }
    if (dropStatus.SelectedIndex ==-1)
    {
      Myfunction.ThongBao(lbThongBao, "Chọn tình trạng sản phẩm !");
      return false;
    }
    if (dropBrand.SelectedIndex == -1)
    {
      Myfunction.ThongBao(lbThongBao, "Chọn thương hiệu sản phẩm !");
      return false;
    }
    decimal cost;
    if (txtCost.Text != "" && !decimal.TryParse(txtCost.Text.Trim(), out cost))
    {
      Myfunction.ThongBao(lbThongBao, "Nhập giá sản phẩm không hợp lệ !");
      txtCost.Focus();
      return false;
    }
    if (txtCost_Sale.Text != "" && !checkNoneSale.Checked && !decimal.TryParse(txtCost_Sale.Text.Trim(), out cost))
    {
      Myfunction.ThongBao(lbThongBao, "Nhập giá sales không hợp lệ !");
      txtCost_Sale.Focus();
      return false;
    }
    int view;
    if (txtView.Text != "" && !int.TryParse(txtView.Text.Trim(), out view))
    {
      Myfunction.ThongBao(lbThongBao, "Nhập số lượng xem không hợp lệ !");
      txtView.Focus();
      return false;
    }
    int quantity;
    if (txtQuantity.Text != "" && !int.TryParse(txtQuantity.Text.Trim(), out quantity))
    {
      Myfunction.ThongBao(lbThongBao, "Nhập số lượng không hợp lệ !");
      txtView.Focus();
      return false;
    }
    DateTime date;
    if (txtCreatedDate.Text != "" && !DateTime.TryParse(txtCreatedDate.Text.Trim(), out date))
    {
      Myfunction.ThongBao(lbThongBao, "Ngày tháng không hợp lệ !");
      txtCreatedDate.Focus();
      return false;     
    }
    if (Request.QueryString["Id"] == null)
    {
        //if (!fileUpload_thumb.HasFile)
        //{
        //    Myfunction.ThongBao(lbThongBao, "Ảnh thumbnails không được để trống !");
        //    return false;
        //}
      if (!file_Image_01.HasFile)
      {
        Myfunction.ThongBao(lbThongBao, "Ảnh thứ nhất là ảnh đại diện không được để trống !");
        return false;
      }
    }
    
    return true;
  }
  private void ResetForm()
  {
    txtMaSP.Text = "";
    txtName.Text = "";
    txtName_En.Text = "";
    txtCost.Text = "";
    txtOrigin.Text = "";

    for (int i = 0; i < checkSize.Items.Count; i++)
    {
      if (checkSize.Items[i].Selected)
        checkSize.Items[i].Selected = false;
    }
    //for (int i = 0; i < checkColour.Items.Count; i++)
    //{
    //  if (checkColour.Items[i].Selected)
    //    checkColour.Items[i].Selected = false;
    //}
    fckEditor.Value = "";
    //fckEditor_En.Value = "";
    txtQuantity.Text = "0";
    
    txtTag.Text = "";
    txtView.Text = "0";
    radioEnable.Checked = true;

    txtOrigin.Text = "";


    checkHot.Checked = false;
    checkKM.Checked = false;
  }
  private void Update()
  {
    string id = Request.QueryString["Id"];
    Product product = productData.GetById(id);
    
    product.Name = txtName.Text;
    product.Name_En = txtName_En.Text;

    if (txtCost.Text != "")
      product.Cost = Convert.ToDecimal(txtCost.Text.Trim());
    if (!checkNoneSale.Checked && txtCost_Sale.Text != "")
      product.Cost_Sale = Convert.ToDecimal(txtCost_Sale.Text.Trim());
    else
      product.Cost_Sale = null;

    
    product.Status = Convert.ToInt32(dropStatus.SelectedValue);
    product.Brand = Convert.ToInt32(dropBrand.SelectedValue);

    product.LabelId = Convert.ToInt32(dropLabel.SelectedValue);
    product.LinkGoc = txtOrigin.Text;
    product.UuDai = txtDescription.Text;

    product.Content = HttpUtility.HtmlEncode(fckEditor.Value);
    //product.Content_En = HttpUtility.HtmlEncode(fckEditor_En.Value);
    product.Quantity = Convert.ToInt32(txtQuantity.Text);
    product.CategoryId = Convert.ToInt32(dropParent.SelectedValue);

    if (txtView.Text != "")
      product.View = Convert.ToInt32(txtView.Text.Trim());
    
    product.Tag = Myfunction.LocDau(txtName.Text.Trim().ToLower()) + " | "
                + Myfunction.LocDau(txtTag.Text.Trim().ToLower());
    product.CreatedDate = Convert.ToDateTime(txtCreatedDate.Text);
    product.isEnable = (radioEnable.Checked ? true : false);

   
    product.isKM = (checkKM.Checked ? true : false);
    product.isHot = (checkHot.Checked ? true : false);

   
      if (file_Image_01.HasFile)
      {
        product.Image_01 = MyGraphics.CopyFile(file_Image_01.PostedFile, "Images/Product", product.Name + "-1-");
      }
      if (file_Image_02.HasFile)
      {
        product.Image_02 = MyGraphics.CopyFile(file_Image_02.PostedFile, "Images/Product", product.Name + "-2-");
      }
      if (file_Image_03.HasFile)
      {
        product.Image_03 = MyGraphics.CopyFile(file_Image_03.PostedFile, "Images/Product", product.Name + "-3-");
      }
      if (file_Image_04.HasFile)
      {
        product.Image_04 = MyGraphics.CopyFile(file_Image_04.PostedFile, "Images/Product", product.Name + "-4-");
      }
      if (file_Image_05.HasFile)
      {
        product.Image_05 = MyGraphics.CopyFile(file_Image_05.PostedFile, "Images/Product", product.Name + "-5-");
      }
      if (file_Image_06.HasFile)
      {
        product.Image_06 = MyGraphics.CopyFile(file_Image_06.PostedFile, "Images/Product", product.Name + "-6-");
      }

      if (check_DelImage_02.Visible && check_DelImage_02.Checked)
      {
        Myfunction.DeleteFile("Images/Product", product.Image_02);
        product.Image_02 = null;
      }
      if (check_DelImage_03.Visible && check_DelImage_03.Checked)
      {
        Myfunction.DeleteFile("Images/Product", product.Image_03);
        product.Image_03 = null;
      }
      if (check_DelImage_04.Visible && check_DelImage_04.Checked)
      {
        Myfunction.DeleteFile("Images/Product", product.Image_04);
        product.Image_04 = null;
      }
      if (check_DelImage_05.Visible && check_DelImage_05.Checked)
      {
        Myfunction.DeleteFile("Images/Product", product.Image_05);
        product.Image_05 = null;
      }
      if (check_DelImage_06.Visible && check_DelImage_06.Checked)
      {
        Myfunction.DeleteFile("Images/Product", product.Image_06);
        product.Image_06 = null;
      }
    productData.Update(product);
    try
    {

        ProductInSizeBLL pisData = new ProductInSizeBLL();
        ProductInColourBLL picData = new ProductInColourBLL();
        pisData.DeleteByProductId(id);
        picData.DeleteByProductId(id);
        for (int i = 0; i < checkSize.Items.Count; i++)
        {
            if (checkSize.Items[i].Selected)
            {
                ProductInSize obj = new ProductInSize();
                obj.IdSize = Convert.ToInt32(checkSize.Items[i].Value);
                obj.IdProduct = id;
                pisData.Add(obj);
            }
        }

        foreach (RepeaterItem item in rptColor.Items)
        {
            CheckBox cbColor = (CheckBox)item.FindControl("CheckBoxList1");
            Label labelId = (Label)item.FindControl("idColors");
            if (cbColor.Checked == true)
            {
                ProductInColour obj = new ProductInColour();
                obj.IdProduct = product.Id;
                obj.IdColour = Convert.ToInt32(labelId.Text);
                picData.Add(obj);
            }
        }

        //for (int i = 0; i < checkColour.Items.Count; i++)
        //{
        //    if (checkColour.Items[i].Selected)
        //    {
        //        ProductInColour obj = new ProductInColour();
        //        obj.IdProduct = id;
        //        obj.IdColour = Convert.ToInt32(checkColour.Items[i].Value);
        //        picData.Add(obj);
        //    }
        //}
    }
    catch { }

    Myfunction.ThongBao(lbThongBao, "Thông tin sản phẩm đã được cập nhật");
  }

  void AddColor()
  {
      
  }

  private void Add()
  {
    Product product = new Product();

    product.Id = txtMaSP.Text;
    product.Name = txtName.Text;
    product.Name_En = txtName_En.Text;

    if (txtCost.Text != "")
      product.Cost = Convert.ToDecimal(txtCost.Text.Trim());

    if (txtCost_Sale.Text != "")
      product.Cost_Sale = Convert.ToDecimal(txtCost_Sale.Text.Trim());

    product.Status = Convert.ToInt32(dropStatus.SelectedValue);
    product.Brand = Convert.ToInt32(dropBrand.SelectedValue);

    product.LabelId = Convert.ToInt32(dropLabel.SelectedValue);
    product.LinkGoc = txtOrigin.Text;
    product.UuDai = txtDescription.Text;

    product.Content = HttpUtility.HtmlEncode(fckEditor.Value);
    //product.Content_En = HttpUtility.HtmlEncode(fckEditor_En.Value);
    product.Quantity = Convert.ToInt32(txtQuantity.Text);
    product.CategoryId = Convert.ToInt32(dropParent.SelectedValue);

    if (txtView.Text != "")
      product.View = Convert.ToInt32(txtView.Text.Trim());

    product.Tag = Myfunction.LocDau(txtName.Text.Trim().ToLower()) + " | "
                + Myfunction.LocDau(txtTag.Text.Trim().ToLower());
    product.CreatedDate = DateTime.Now;
    product.isEnable = (radioEnable.Checked ? true : false);


    product.isKM = (checkKM.Checked ? true : false);
    product.isHot = (checkHot.Checked ? true : false);


    if (file_Image_01.HasFile)
    {
      product.Image_01 = MyGraphics.CopyFile(file_Image_01.PostedFile, "Images/Product", product.Name + "-1-");
    }
    if (file_Image_02.HasFile)
    {
      product.Image_02 = MyGraphics.CopyFile(file_Image_02.PostedFile, "Images/Product", product.Name + "-2-");
    }
    if (file_Image_03.HasFile)
    {
      product.Image_03 = MyGraphics.CopyFile(file_Image_03.PostedFile, "Images/Product", product.Name + "-3-");
    }
    if (file_Image_04.HasFile)
    {
      product.Image_04 = MyGraphics.CopyFile(file_Image_04.PostedFile, "Images/Product", product.Name + "-4-");
    }
    if (file_Image_05.HasFile)
    {
      product.Image_05 = MyGraphics.CopyFile(file_Image_05.PostedFile, "Images/Product", product.Name + "-5-");
    }
    if (file_Image_06.HasFile)
    {
      product.Image_06 = MyGraphics.CopyFile(file_Image_06.PostedFile, "Images/Product", product.Name + "-6-");
    }
    productData.Add(product);

    //Update Product Size and Product COlour
    ProductInSizeBLL pisData = new ProductInSizeBLL();
    ProductInColourBLL picData = new ProductInColourBLL();

    for (int i = 0; i < checkSize.Items.Count; i++)
    {
        if (checkSize.Items[i].Selected)
        {
            ProductInSize obj = new ProductInSize();
            obj.IdSize = Convert.ToInt32(checkSize.Items[i].Value);
            obj.IdProduct = product.Id;
            pisData.Add(obj);
        }
    }


    foreach (RepeaterItem item in rptColor.Items)
    {
            CheckBox cbColor = (CheckBox)item.FindControl("CheckBoxList1");
            Label labelId = (Label)item.FindControl("idColors");
            if (cbColor.Checked == true)
            {
                ProductInColour obj = new ProductInColour();
                obj.IdProduct = product.Id;
                obj.IdColour = Convert.ToInt32(labelId.Text);
                picData.Add(obj);
            }
    }



    //for (int i = 0; i < checkColour.Items.Count; i++)
    //{
    //    if (checkColour.Items[i].Selected)
    //    {
    //        ProductInColour obj = new ProductInColour();
    //        obj.IdProduct = product.Id;
    //        obj.IdColour = Convert.ToInt32(checkColour.Items[i].Value);
    //        picData.Add(obj);
    //    }
    //}
    Myfunction.ThongBao(lbThongBao, "Thông tin sản phẩm đã được cập nhật !");
  }
 
  protected void btnOk_Click(object sender, EventArgs e)
  {
    //if ((int)Session["Role"] != 1)
    //{
    //  Myfunction.ThongBao(lbThongBao, "Bạn không có quyền thực hiện thao tác này ! ");
    //  return;
    //}
    //try
    //{
      lbThongBao.Text = "";
      if (isValidate())
      {
        if (Request.QueryString["Id"] == null)
        {
          Add();
          ResetForm();
        }
        else
          Update();

      }
    //}
    //catch (Exception ex)
    //{
    //  Myfunction.ThongBao(lbThongBao, ex.Message);
    //}
  }

  protected void dropParent_SelectedIndexChanged(object sender, EventArgs e)
  {
    LoadSize();
    LoadColour();
    LoadBrand();
    LoadrptColor();
    LoadControl();
  }
  protected void rptColor_ItemDataBound(object sender, RepeaterItemEventArgs e)
  {
      if (dropParent.SelectedIndex == -1) return;
      string IdProduct = "1";
      if (Request.QueryString["Id"] != null)
      {
          try { IdProduct = Request.QueryString["Id"]; }
          catch { }
      }
      
      DataRowView dtItem = (DataRowView)e.Item.DataItem;
      if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
      {
          
          CheckBox cbColor = (CheckBox)e.Item.FindControl("CheckBoxList1");
          Label labelId = (Label)e.Item.FindControl("idColors");
          //Load color
          var listColor = picData.GetByProductId(IdProduct.ToString());
          foreach (var item in listColor)
          {
                  if (labelId.Text == item.IdColour.ToString())
                      cbColor.Checked= true;
          }
      }
  }
}